<template>
  <view class="admin-feedback-detail">
    <view class="page-header">
      <view class="back-btn" @click="goBack">
        <view class="icon" style="font-size: 20px;">‹</view>
        <text class="header-title">反馈详情</text>
      </view>
    </view>
    
    <view v-if="loading" class="loading-container">
      <uni-load-more :status="'loading'" />
    </view>
    
    <view v-else-if="feedback" class="feedback-detail-content">
      <!-- 反馈基本信息 -->
      <view class="feedback-info">
        <view class="info-row">
          <text class="label">反馈用户：</text>
          <text class="value">{{ feedback.userId?.substring(0, 8) || '匿名用户' }}</text>
        </view>
        
        <view class="info-row">
          <text class="label">提交时间：</text>
          <text class="value">{{ formatTime(feedback.createTime) }}</text>
        </view>
        
        <view class="info-row" v-if="feedback.updateTime">
          <text class="label">更新时间：</text>
          <text class="value">{{ formatTime(feedback.updateTime) }}</text>
        </view>
        
        <view class="info-row">
          <text class="label">当前状态：</text>
          <text class="value status-badge" :class="`status-${feedback.status}`">
            {{ getStatusText(feedback.status) }}
          </text>
        </view>
        
        <view class="info-row" v-if="feedback.contact">
          <text class="label">联系方式：</text>
          <text class="value contact" @click="copyContact">{{ feedback.contact }}</text>
        </view>
      </view>
      
      <!-- 反馈内容 -->
      <view class="content-section">
        <text class="section-title">反馈内容</text>
        <text class="feedback-content">{{ feedback.content }}</text>
      </view>
      
      <!-- 反馈图片 -->
      <view class="content-section" v-if="feedback.imageList && feedback.imageList.length > 0">
        <text class="section-title">反馈图片</text>
        <view class="image-grid">
          <image 
            v-for="(image, index) in feedback.imageList" 
            :key="index" 
            :src="image" 
            mode="aspectFill" 
            class="feedback-image"
            @click="previewImage(image, index)"
          ></image>
        </view>
      </view>
      
      <!-- 状态更新 -->
      <view class="content-section">
        <text class="section-title">处理状态</text>
        <view class="status-update">
          <!-- 使用正确的radio-group实现 -->
          <view>
            <radio-group @change="onStatusChange">
              <label><radio :value="'pending'" :checked="currentStatus === 'pending'" /> 待处理</label>
              <label><radio :value="'processing'" :checked="currentStatus === 'processing'" /> 处理中</label>
              <label><radio :value="'resolved'" :checked="currentStatus === 'resolved'" /> 已解决</label>
            </radio-group>
          </view>
        </view>
      </view>
      
      <!-- 历史备注信息 -->
      <view class="content-section" v-if="feedback.remark">
        <text class="section-title">历史备注</text>
        <view class="history-remark">
          <text class="remark-content">{{ feedback.remark }}</text>
        </view>
      </view>
      
      <!-- 备注信息 -->
      <view class="content-section">
        <text class="section-title">处理备注</text>
        <textarea 
          v-model="remark" 
          placeholder="请输入处理备注（可选）" 
          class="remark-input"
          auto-height
        ></textarea>
      </view>
      
      <!-- 操作按钮 -->
      <view class="action-buttons">
        <button 
          type="primary" 
          @click="updateFeedbackStatus"
          :loading="submitting"
          :disabled="submitting || !canSubmit"
        >
          保存状态
        </button>
      </view>
    </view>
    
    <view v-else class="error-container">
      <text class="error-text">无法加载反馈信息</text>
      <button type="default" @click="goBack">返回列表</button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import {  onLoad, onShow } from "@dcloudio/uni-app"

// 响应式数据
const feedback = ref(null);
const loading = ref(true);
const submitting = ref(false);
const currentStatus = ref('pending'); // 重命名以避免混淆
const remark = ref('');
const id = ref('');

// 计算属性
const canSubmit = computed(() => {
  // 只有当状态发生变化时才允许提交
  return feedback.value && feedback.value.status !== currentStatus.value;
});

// 生命周期
onLoad((options) => {
  id.value = options.id || '';
  // 移除管理员权限校验
  getFeedbackDetail();
});

onShow(() => {
  // 页面显示时可以重新获取数据
  if (id.value) {
    getFeedbackDetail();
  }
});

// 管理员权限校验已移除

// 获取反馈详情
const getFeedbackDetail = async () => {
  if (!id.value) {
    loading.value = false;
    return;
  }
  
  loading.value = true;
  
  try {
    const res = await uniCloud.callFunction({
      name: 'getFeedbackDetail',
      data: {
        id: id.value
      }
    });
    
    console.log('获取反馈详情结果:', res);
    
    if (res && res.result && res.result.success) {
      // 直接使用data，而不是data[0]
      feedback.value = res.result.data[0];
      
      // 设置初始状态
      const validStatuses = ['pending', 'processing', 'resolved'];
      const status = feedback.value.status;
      
      if (status && validStatuses.includes(status)) {
        currentStatus.value = status;
      } else {
        currentStatus.value = 'pending'; // 默认设置为待处理
      }
      
      console.log('设置currentStatus:', currentStatus.value);
    } else {
      uni.showToast({ 
        title: '获取详情失败', 
        icon: 'none' 
      });
    }
  } catch (error) {
    console.error('获取反馈详情失败:', error);
    uni.showToast({ 
      title: '网络错误，请稍后重试', 
      icon: 'none' 
    });
  } finally {
    loading.value = false;
  }
};

// 状态变更处理
const onStatusChange = (e) => {
  currentStatus.value = e.detail.value;
};

// 更新反馈状态
const updateFeedbackStatus = async () => {
  if (!feedback.value || submitting.value) return;
  
  submitting.value = true;
  
  try {
    const res = await uniCloud.callFunction({
      name: 'updateFeedback',
      data: {
        id: feedback.value._id,
        status: currentStatus.value,
        remark: remark.value
      }
    });
    
    if (res && res.result && res.result.success) {
      uni.showToast({ 
        title: '状态更新成功', 
        icon: 'success' 
      });
      
      // 更新本地数据
      feedback.value.status = currentStatus.value;
      if (remark.value) {
        feedback.value.remark = remark.value;
      }
    } else {
      uni.showToast({ 
        title: '状态更新失败', 
        icon: 'none' 
      });
    }
  } catch (error) {
    console.error('更新反馈状态失败:', error);
    uni.showToast({ 
      title: '网络错误，请稍后重试', 
      icon: 'none' 
    });
  } finally {
    submitting.value = false;
  }
};

// 格式化时间
const formatTime = (time) => {
  if (!time) return '';
  const date = new Date(time);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
};

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待处理',
    'processing': '处理中',
    'resolved': '已解决'
  };
  return statusMap[status] || '未知状态';
};

// 复制联系方式
const copyContact = () => {
  if (feedback.value && feedback.value.contact) {
    uni.setClipboardData({
      data: feedback.value.contact,
      success: () => {
        uni.showToast({
          title: '已复制联系方式',
          icon: 'success'
        });
      }
    });
  }
};

// 预览图片
const previewImage = (currentImage, index) => {
  if (feedback.value && feedback.value.imageList) {
    uni.previewImage({
      current: index,
      urls: feedback.value.imageList
    });
  }
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style scoped lang="less">
.admin-feedback-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
  
  .page-header {
    padding: 16px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    margin-top: 40rpx;
    .back-btn {
      display: flex;
      align-items: center;
      
      .icon {
        color: #333;
      }
      
      .header-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-left: 8px;
      }
    }
  }
  
  .loading-container {
    padding: 40px 0;
    display: flex;
    justify-content: center;
  }
  
  .error-container {
    padding: 40px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .error-text {
      font-size: 14px;
      color: #666;
      margin-bottom: 20px;
    }
  }
  
  .feedback-detail-content {
    padding: 16px;
    
    .feedback-info {
      background-color: #fff;
      border-radius: 12px;
      padding: 16px;
      margin-bottom: 16px;
      
      .info-row {
        display: flex;
        margin-bottom: 12px;
        align-items: center;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .label {
          font-size: 14px;
          color: #666;
          width: 80px;
        }
        
        .value {
          font-size: 14px;
          color: #333;
          flex: 1;
        }
        
        .contact {
          color: #1989fa;
          cursor: pointer;
        }
        
        .status-badge {
          padding: 4px 12px;
          border-radius: 12px;
          font-size: 12px;
          
          &.status-pending {
            background-color: #f5f5f5;
            color: #666;
          }
          
          &.status-processing {
            background-color: #e6f7ff;
            color: #1890ff;
          }
          
          &.status-resolved {
            background-color: #f6ffed;
            color: #52c41a;
          }
        }
      }
    }
    
    .content-section {
        background-color: #fff;
        border-radius: 12px;
        padding: 16px;
        margin-bottom: 16px;
        
        .section-title {
          font-size: 16px;
          font-weight: 600;
          color: #333;
          margin-bottom: 12px;
          display: block;
        }
        
        .history-remark {
          background-color: #f9f9f9;
          border-radius: 8px;
          padding: 12px;
          
          .remark-content {
            font-size: 14px;
            color: #666;
            line-height: 1.6;
          }
        }
      
      .feedback-content {
        font-size: 14px;
        color: #333;
        line-height: 1.6;
        word-break: break-all;
      }
      
      .image-grid {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;
        
        .feedback-image {
          width: 100%;
          aspect-ratio: 1;
          border-radius: 8px;
        }
      }
      
      .status-update {
        padding: 8px 0;
        
        label {
          display: block;
          margin-bottom: 12px;
          font-size: 14px;
          color: #333;
        }
      }
      
      .remark-input {
        border: 1px solid #e5e5e5;
        border-radius: 8px;
        padding: 12px;
        font-size: 14px;
        color: #333;
        min-height: 100px;
        box-sizing: border-box;
      }
    }
    
    .action-buttons {
      padding: 16px 0;
      
      button {
        width: 100%;
        font-size: 16px;
        height: 48px;
        line-height: 48px;
      }
    }
  }
}
</style>